package com.zz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.common.R;
import com.zz.dto.RolePermissionDto;
import com.zz.entity.Permission;
import com.zz.entity.Role;
import com.zz.entity.RolePermission;
import com.zz.mapper.PermissionMapper;
import com.zz.mapper.RoleMapper;
import com.zz.mapper.RolePermissionMapper;
import com.zz.service.RolePermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HUAWEI
 */
@Service
@Slf4j
@Validated
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public R<Page> page(int page, int pageSize, @Nullable String roleRealName, @Nullable String permissionName) {
        log.info("RolePermissionController=>>>page方法开始执行！");
        // 构造分页构造器
        Page<RolePermission> pageInfo = new Page<>(page, pageSize);
        Page<RolePermissionDto> rolePermissionDtoPage = new Page<>(page, pageSize);

        // 条件过滤器
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();

        // 如果角色显示名不为空
        if (roleRealName != null){
            // 条件查询器
            LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.like(roleRealName != null, Role::getRealname, roleRealName);
            List<Role> roleList = roleMapper.selectList(roleWrapper);
            log.info("roleList=>{}",roleList);
            ArrayList<Integer> roleIds = new ArrayList<>();

            // 遍历所有角色
            for (Role role : roleList) {
                roleIds.add(role.getId());
            }
            if (roleIds.isEmpty()){
                return R.error("查询的角色不存在！");
            }

            wrapper.in(RolePermission::getRoleId, roleIds);
        }

        // 如果用权限名不为空
        if (permissionName != null){
            // 条件查询器
            LambdaQueryWrapper<Permission> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.like(permissionName != null, Permission::getInfo, permissionName);
            List<Permission> permissionList = permissionMapper.selectList(userWrapper);
            List<Integer> permissionIds = new ArrayList<>();
            // 遍历所有用户
            for (Permission permission : permissionList) {
                permissionIds.add(permission.getId());
            }

            if (permissionIds.isEmpty()){
                return R.error("查询的权限不存在！");
            }
            wrapper.in(RolePermission::getPermissionId, permissionIds);
        }

        // 执行分页查询
        // 在page方法内部会将查好的数据封装，赋好值给pageInfo
        rolePermissionMapper.selectPage(pageInfo, wrapper);

        // 对象拷贝(除了records,records其实就是页面中一整行一整行数据)
        BeanUtils.copyProperties(pageInfo,rolePermissionDtoPage,"records");

        List<RolePermission> records = pageInfo.getRecords();
        // 遍历list集合对象,item即为获取到的一个个rolePermission对象
        List<RolePermissionDto> list = records.stream().map((item) -> {
            RolePermissionDto rolePermissionDto = new RolePermissionDto();
            // 将其rolePermission中的数据复制给rolePermissionDto
            BeanUtils.copyProperties(item, rolePermissionDto);

            int roleId = item.getRoleId();
            int permissionId = item.getPermissionId();

            // 根据id查询分类对象
            Role role = roleMapper.selectById(roleId);
            Permission permission = permissionMapper.selectById(permissionId);

            if(role != null){
                rolePermissionDto.setRoleName(role.getName());
                rolePermissionDto.setRoleDesc(role.getDescription());
                rolePermissionDto.setRoleRealName(role.getRealname());
            }

            rolePermissionDto.setPermissionPath(permission.getPath());
            rolePermissionDto.setPermissionInfo(permission.getInfo());

            return rolePermissionDto;
        }).collect(Collectors.toList());// 把以上创建的dto对象都收集起来

        rolePermissionDtoPage.setRecords(list);

        return R.success(rolePermissionDtoPage);
    }

    @Override
    public R<String> add(RolePermission rolePermission) {
        // 条件查询器
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        // 过滤条件
        wrapper.eq(RolePermission::getRoleId, rolePermission.getRoleId());
        wrapper.eq(RolePermission::getPermissionId, rolePermission.getPermissionId());

        // 从数据库中查询此角色权限
        RolePermission one = rolePermissionMapper.selectOne(wrapper);

        if(one != null){
            return R.error("此角色权限已存在！");
        }

        // 数据库中增加角色权限
        rolePermissionMapper.insert(rolePermission);

        return R.success("此角色权限成功增加！");
    }

    @Override
    public R<String> delete(RolePermission rolePermission) {
        // 条件查询器
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        // 条件过滤
        wrapper.eq(RolePermission::getRoleId, rolePermission.getRoleId());
        wrapper.eq(RolePermission::getPermissionId, rolePermission.getPermissionId());

        //从数据库中删除数据
        rolePermissionMapper.delete(wrapper);

        return R.success("成功删除角色权限！");
    }

    @Override
    public R<String> update(RolePermission rolePermission) {
        // 条件查询
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        // 判断此用户角色是否存在
        wrapper.eq(RolePermission::getId, rolePermission.getId());
        RolePermission one1 = rolePermissionMapper.selectOne(wrapper);
        if(one1 == null){
            return R.error("此角色权限不存在，无法修改！");
        }
        // 判断此角色权限是否重复
        wrapper.eq(RolePermission::getRoleId, rolePermission.getRoleId()).eq(RolePermission::getPermissionId, rolePermission.getPermissionId());
        RolePermission one2 = rolePermissionMapper.selectOne(wrapper);
        if(one2 != null){
            return R.error("该角色权限已经存在，修改失败！");
        }

        rolePermissionMapper.updateById(rolePermission);
        return R.success("修改成功！");
    }
}
